import React, { createRef } from 'react';
import classNames from 'classnames';
import type Option from './Option';

export interface SelectProps {
	children?: React.ReactNode;
	className?: string;
	defaultValue?: string;

	//onChange?: (e: React.MouseEvent<HTMLElement>) => void;
}

export interface SelectState {
	value: any;
	focused: boolean;
	/** `value` from prev props */
	prevValue: any;
}

class Select extends React.Component<SelectProps, SelectState> {
	static Option: typeof Option;
	render () {
		const prefixCls = 'bh-select';
		const {
			children,
			className,
			defaultValue,
			...restProps
		} = this.props;
		let currentVal = defaultValue;
		const classString = classNames(
			prefixCls,
			className,
			`${prefixCls}-single`,
			`${prefixCls}-show-arrow`,
		);
		const selectRef:any = createRef();
		const optionRef:any = createRef();
		let openOptionFlag = false;
		//点击打开下拉框
		const onClickHandle = (e: React.MouseEvent<HTMLElement>) => {
			e.stopPropagation();
			openOptionFlag = true;
			const offset:any = selectRef.current.getBoundingClientRect();
			//+滚动位移
			const left:number = offset.left + document.documentElement.scrollLeft;
			const top:number = offset.top + document.documentElement.scrollTop;
			console.log('offset', offset);

			optionRef.current.style.display = 'block';
			optionRef.current.style.left = left + 'px';
			optionRef.current.style.width = selectRef.current.clientWidth + 'px';
			optionRef.current.style.top = (top + 46) + 'px';
		}
		//点击空白关闭下拉框
		document.addEventListener('click', (e:any) => {
			if(openOptionFlag) {
				console.log('all click');
				if(e.target.classList.contains('bh-select-item-option')) {
					console.log(e.target.classList);
					currentVal = e.target.attributes.value || '';
					console.log(currentVal);
				}
				optionRef.current.style.display = 'none';
				openOptionFlag = false;
			}
		})
		//将下拉部分插入body里
		setTimeout(() => {
			try{
			    document.body.appendChild(optionRef.current)
			}catch(e:any) {}
		}, 200)

		return (
			<div {...restProps} className={classString} ref={selectRef} onClick={onClickHandle}>
			    <span className="bh-select-selector">
			    	<span className="bh-select-selection-search">
			    		<input className="bh-select-selection-search-input" />
			    	</span>
			        <span className="bh-select-selection-item">{currentVal}</span>
			    </span>
			    <span className="bh-select-arrow">
			    	<i className="bh-icon bh-icon-arrow-down"></i>
			    </span>
			    <div className="bh-select-dropdown" ref={optionRef}>
			        <div className="bh-select-dropdown-inter">
			            {children}
			        </div>
			    </div>
			</div>
		)
	}
};

//Select.Option = Option;

export default Select;